<template>
  <div class="car">
    <van-checkbox-group v-model="result">
      <van-checkbox
        :name="item"
        v-for="item in cartList"
        :key="item.id"
        @click="singleCheckFn"
      >
        <van-card
          :num="item.number"
          :price="item.retail_price"
          desc="描述信息"
          :title="item.goods_name"
          :thumb="item.list_pic_url"
        />
          <van-button size="mini" @click="delgoods(item)">删除</van-button>
      </van-checkbox>
    </van-checkbox-group>
    <!-- 提交订单 -->
    <van-submit-bar
      :price="totalPrice"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-checkbox v-model="checked" @click="checkAllFn">全选</van-checkbox>
      <template #tip>
        你的收货地址不支持同城送,
        <span @click="onClickEditAddress">修改地址</span>
      </template>
    </van-submit-bar>
  </div>
</template>

<script>
// 导入购物车接口请求
import { getCarData,PostShanChu } from "@/utils/http";
export default {
  name: "Car",
  props: [""],
  data() {
    return {
      result: [], //复选框选中的商品
      cartList: [], //购物车数据
      checked: false, //全选状态
    };
  },

  components: {},

  computed: {
    // 计算属性
    totalPrice() {
      let sum = 0;
      this.result.forEach((item) => {
        sum += item.market_price * item.number * 100;
      });
      return sum;
    },
  },

  created() {
    getCarData().then((res) => {
      console.log(res);
      this.cartList = res.data.data.cartList;
    });
  },

  mounted() {},

  methods: {
    onSubmit() {
      // 提交订单
      console.log(this.result);
    },
    onClickEditAddress() {
      //修改地址
    },
    checkAllFn() {
      // 全选事件
      console.log(this.checked);
      if (this.checked) {
        this.result = this.cartList;
      } else {
        this.result = [];
      }
    },
    singleCheckFn() {
      //单选事件
      if (
        this.result.length == this.cartList.length &&
        this.cartList.length != 0
      ) {
        this.checked = true;
      } else {
        this.checked = false;
      }
    },
    delgoods(item){
      // 删除商品
      PostShanChu({productIds:String(item.product_id)}).then((res)=>{
         // 重新渲染购物车数据
        this.cartList = res.data.data.cartList;
        // 初始化单选状态
        this.result = []; // 清空
      })
    }
  },
};
</script>
<style lang='less' scoped>
/deep/.van-checkbox__label {
  flex: 1;
}
/deep/.van-checkbox-group{
  padding-bottom: 100px;
}
/deep/.van-submit-bar {
  bottom: 50px;
}
.van-button--default{
  bottom: 70px;
  left: 300px;
}
</style>